package com.mallbook.model.service;

import com.mallbook.model.exception.AddressDefaultNumMuchException;
import com.mallbook.model.exception.AddressNumMuchException;
import com.mallbook.model.exception.ServiceException;
import com.mallbook.model.pojo.Address;
import com.mallbook.model.mapper.AddressMapper;
import com.mallbook.model.mapper.RegionMapper;
import com.mallbook.model.utils.MallDefaultConfig;
import com.mallbook.model.utils.MybatisUtils;
import org.apache.ibatis.exceptions.PersistenceException;

import java.util.List;

/**
 * @Author 宋明松
 * @Version V1.0.0
 * @Date 2022-06-25
 * 收货地址service层
 */
public class AddressService {


    /**
     * 新增地址，用户ID封装到address中
     * （总数5条，有且仅有一个默认地址）
     *
     * @param username 收件人
     * @param sfId     省份ID
     * @param sId      市ID
     * @param qId      区ID
     * @param street   街道
     * @param tel      电话号
     * @param state    状态 代表删除-1，1代表不删除，2代表默认，默认为1
     * @param uId      用户ID
     */
    public void addAddress(String username, Integer sfId, Integer sId, Integer qId, String street, String tel, Integer state, Integer uId) {
        AddressMapper addressMapper = MybatisUtils.getMappers(AddressMapper.class);
        RegionMapper regionMapper = MybatisUtils.getMappers(RegionMapper.class);
        Address address = new Address();
        address.setConsignee(username);
        address.setProvince(regionMapper.findRegionById(sfId).getName());
        address.setCity(regionMapper.findRegionById(sId).getName());
        address.setArea(regionMapper.findRegionById(qId).getName());
        address.setTel(tel);
        address.setStreet(street);
        address.setState(state);
        address.setUserId(uId);

        // 查询该用户所拥有的地址数量
        int addressNums = 0;
        try {
            addressNums = addressMapper.findAddressBySumNum(address.getUserId());
        } catch (PersistenceException e) {
            throw new ServiceException("数据操作异常", e);
        }
        // 第一次新增地址，直接设为默认地址,直接新增
        if (addressNums == 0) {
            address.setState(2);
            try {
                addressMapper.add(address);
            } catch (PersistenceException e) {
                throw new ServiceException("数据操作异常", e);
            }
        } else if (addressNums >= MallDefaultConfig.MAX_ADDRESS) {
            throw new AddressNumMuchException("最多只能拥有" + MallDefaultConfig.MAX_ADDRESS + "个收货地址");
        } else {

            // 查询该用户所拥有的默认地址数量
            try {
                if (address.getState() == 2) {
                    int defaultAddressNums = addressMapper.findDefaultAddressNums(address.getUserId());
                    if (defaultAddressNums == 1) {
                        throw new AddressDefaultNumMuchException("最多只能拥有一个默认地址");
                    }
                }
                addressMapper.add(address);
            } catch (PersistenceException e) {
                throw new ServiceException("数据操作异常", e);
            }
        }
    }

    /**
     * 删除地址，默认地址无法删除，界面控制
     *
     * @param aId 地址ID
     * @param uId 用户ID
     */
    public void delAddress(Integer aId, Integer uId) {
        AddressMapper addressMapper = MybatisUtils.getMappers(AddressMapper.class);
        try {
            Address address = addressMapper.findAddressById(aId, uId);
            if (address.getState() == 2) {
                throw new AddressDefaultNumMuchException("至少需要一个默认地址");
            }
            addressMapper.delete(aId, uId);
        } catch (PersistenceException e) {
            throw new ServiceException("数据操作异常", e);
        }
    }

    /**
     * 修改地址
     *
     * @param username 收件人
     * @param sfId     省份ID
     * @param sId      市ID
     * @param qId      区ID
     * @param street   街道
     * @param tel      电话号
     * @param state    状态 代表删除-1，1代表不删除，2代表默认，默认为1
     * @param uId      用户ID
     * @param id       地址ID
     */
    public void updateAddress(String username, Integer sfId, Integer sId, Integer qId, String street, String tel, Integer state, Integer uId, Integer id) {
        AddressMapper addressMapper = MybatisUtils.getMappers(AddressMapper.class);
        RegionMapper regionMapper = MybatisUtils.getMappers(RegionMapper.class);
        Address address = new Address();
        address.setConsignee(username);
        address.setProvince(regionMapper.findRegionById(sfId).getName());
        address.setCity(regionMapper.findRegionById(sId).getName());
        address.setArea(regionMapper.findRegionById(qId).getName());
        address.setTel(tel);
        address.setStreet(street);
        address.setState(state);
        address.setId(id);

        // 判断是否修改了默认地址
        try {
            if (address.getState() != 2) {
                Address a = addressMapper.findAddressById(id, uId);
                if (a.getState() == 2) {
                    throw new AddressDefaultNumMuchException("至少需要一个默认地址");
                }
            }
            address.setUserId(uId);
            addressMapper.update(address);
        } catch (PersistenceException e) {
            throw new ServiceException("数据操作异常", e);
        }
    }

    /**
     * 查询用户的一条地址
     *
     * @param aId 地址ID
     * @param uId 用户ID
     * @return
     */
    public Address getAddress(Integer aId, Integer uId) {
        AddressMapper addressMapper = MybatisUtils.getMappers(AddressMapper.class);
        try {
            return addressMapper.findAddressById(aId, uId);
        } catch (PersistenceException e) {
            throw new ServiceException("数据操作异常", e);
        }

    }

    /**
     * 查询该用户的所有地址信息
     *
     * @param uId 用户ID
     * @return
     */
    public List<Address> getAllAddress(Integer uId) {
        AddressMapper addressMapper = MybatisUtils.getMappers(AddressMapper.class);
        try {
            return addressMapper.findAllAddress(uId);
        } catch (PersistenceException e) {
            throw new ServiceException("数据操作异常", e);
        }
    }

    /**
     * 查询该用户的默认地址信息
     *
     * @param uId 用户ID
     * @return
     */
    public Address getDefaultAddress(Integer uId) {
        AddressMapper addressMapper = MybatisUtils.getMappers(AddressMapper.class);
        try {
            return addressMapper.findDefaultAddress(uId);
        } catch (PersistenceException e) {
            throw new ServiceException("数据操作异常", e);
        }
    }

    public void setDefaultAddress(Integer uid, Integer aid) {
        AddressMapper addressMapper = MybatisUtils.getMappers(AddressMapper.class);
        try {
            Address deAddress = addressMapper.findDefaultAddress(uid);
            Address upAddress = new Address();
            upAddress.setUpstate(2);//条件
            upAddress.setState(1);
            upAddress.setUserId(deAddress.getUserId());
            upAddress.setId(deAddress.getId());
            addressMapper.update(upAddress); //修改默认地址为1

            Address setAddress = new Address(); // 设置默认地址
            setAddress.setUserId(uid);
            setAddress.setId(aid);
            setAddress.setState(2);
            addressMapper.update(setAddress);
        } catch (PersistenceException e) {
            throw new ServiceException("数据操作异常", e);
        }
    }
}